
package misc

import (
	"time"
	"dhfshop/models"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type PushMsgQueue struct {
	Id           int64     `orm:"column(id);pk;auto" json:"id" form:"id"`                    //消息ID
	PartnerId    int64     `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`    //组织编号
	StoreId      int64     `orm:"column(store_id)" json:"store_id" form:"store_id"`          //门店编号
	MsgBody      string    `orm:"column(msg_body)" json:"msg_body" form:"msg_body"`          //消息体
	Status       string    `orm:"column(status);null" json:"status" form:"status"`           //是否推送成功
	CreatedAt    time.Time `orm:"column(created_at);auto_now_add;type(datetime)" json:"-"`
	CreatedAtStr string    `orm:"-" json:"created_at"`
}

func init() {
	orm.RegisterModel(new(PushMsgQueue))
}

func AddPushMsgQueue(pushMsgQueue *PushMsgQueue) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(pushMsgQueue)
	return
}

func GetAllPushMsgQueues(partnerId int64,start,end,status string,offset,limit int)([]*PushMsgQueue,int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(PushMsgQueue))
	if len(start) == 19 {
	    if startTime, err := time.Parse(consts.DATETIME_FORMAT, start); err == nil {
		    qs = qs.Filter("created_at__gte", startTime)
		}
	}
	if len(end) == 19 {
	    if endTime, err := time.Parse(consts.DATETIME_FORMAT, end); err == nil {
		    qs = qs.Filter("created_at__lte", endTime)
		}
	}
	if len(status) > 0 {
	    qs = qs.Filter("status", status)
	}
	cnt, err := qs.Count()
	qs = qs.OrderBy("created_at")
	var lists []*PushMsgQueue
	if _, err = qs.Limit(limit, offset).All(&lists); err == nil {
		for _, item := range lists {
			item.CreatedAtStr = item.CreatedAt.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdatePushMsgQueueById(m *PushMsgQueue, fields ...string) error {
	o := models.GetDefaultDB()
	v := PushMsgQueue{Id: m.Id}
	if err := o.Read(&v); err != nil {
		return err
	}
	_, err := o.Update(m, fields...)
	return err
}

func DeletePushMsgQueueById(Id int64) (err error) {
	o := models.GetDefaultDB()
	v := PushMsgQueue{Id: Id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
